
package com.yuan.unit;

import com.yuan.prefence.FileConstants;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageUtils {
    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 30) { // 循环判断如果压缩后图片是否大于30kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            options -= 10;// 每次都减少10
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    /**
     * 可能情况：防止第一次下载的图片覆盖第二次 第一次的图片比较大 并对图片进行存储
     * 
     * @throws IOException
     */
    public static synchronized Bitmap LoadImageView(final Context mContext, final String ImageUrl)
            throws IOException {
        if (isHadBitmap(StringUtils.MD5Encode(ImageUrl)))
        {
            return getBitmapToFileSystem(mContext,
                    FileConstants.LOCAL_PATH_IMAGES, StringUtils.MD5Encode(ImageUrl));
        }
        else
        {
            Bitmap mBitmap = null;
            URL url = new URL(ImageUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream inputStream = conn.getInputStream();
            mBitmap = BitmapFactory.decodeStream(inputStream);
            mBitmap = compressImage(mBitmap);
            saveBitmapToFileSystem(mContext, FileConstants.LOCAL_PATH_IMAGES,
                    StringUtils.MD5Encode(ImageUrl), mBitmap);
            conn.disconnect();

            return mBitmap;
        }

    }

    private static boolean isHadBitmap(String path) {
        // TODO Auto-generated method stub
        if (path == null)
            return false;
        File thumbNail = new File(FileConstants.LOCAL_PATH_IMAGES, path);
        if (thumbNail == null || !thumbNail.exists()) {
            return false;
        }
        return true;
    }

    public static void writeFileFromStream(InputStream stream, File file)
            throws FileNotFoundException, IOException {
        Utils.copyStream(stream, new FileOutputStream(file));
    }

    public static synchronized boolean saveBitmapToFileSystem(Context context, String name,
            final Bitmap bitmap) {
        return saveBitmapToFileSystem(context, context.getFileStreamPath(name).getParentFile()
                .getAbsolutePath(),
                name, bitmap);
    }

    public static synchronized boolean deleteBitmapInFileSystem(Context context, String name) {
        File thumbNail = new File(context.getFileStreamPath(name).getAbsolutePath());
        if (thumbNail.exists()) {
            return thumbNail.delete();
        }
        return false;
    }

    public static synchronized boolean saveBitmapToFileSystem(Context context, String path,
            String name,
            final Bitmap bitmap) {
        // File sdcardDir =Environment.getExternalStorageDirectory();
        // 得到一个路径，内容是sdcard的文件夹路径和名字
        // String path=sdcardDir.getPath()+"/cardImages";
        File thumbNail = new File(path, name);
        if (thumbNail != null) {
            thumbNail.delete();
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(thumbNail);
            if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                out.flush();
            }
            return true;
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    public static Bitmap getBitmapToFileSystem(Context context, String name) {
        return getBitmapToFileSystem(context, context.getFileStreamPath(name).getAbsolutePath(),
                name);
    }

    public static Bitmap getBitmapToFileSystem(Context context, String path, String name) {
        Bitmap mBitmap = null;
        if (context == null) {
            return null;
        }
        File thumbNail = new File(path, name);
        if (thumbNail != null && thumbNail.exists()) {
            try {
                InputStream inputStream = new FileInputStream(thumbNail);
                mBitmap = BitmapFactory.decodeStream(inputStream);
                return mBitmap;
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }
}
